package JUC;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkJoinTaskDemo {



    public static void main(String[] args) throws ExecutionException, InterruptedException {

        MyTask myTask = new MyTask(0,100);

        ForkJoinPool threadPool = new ForkJoinPool();

        ForkJoinTask<Integer> submit = threadPool.submit(myTask);

        System.out.println(submit.get());

        threadPool.shutdown();


    }
}

class MyTask extends RecursiveTask<Integer>{

    private static final int ADJUST_SIZE = 10;

    private int start;
    private int end;
    private int result;

    MyTask(int start, int end) {
        this.start = start;
        this.end = end;
    }


    @Override
    protected Integer compute() {

        if (end - start <=ADJUST_SIZE){
            for (int i = start; i <= end; i++) {
                result = result + i;
            }
        }else {
            int middle = (start+end)/2;
            MyTask myTask1 = new MyTask(start,middle);
            MyTask myTask2 = new MyTask(middle+1,end);
            myTask1.fork();
            myTask2.fork();
            result = myTask2.join()+ myTask1.join();
        }
        return result;
    }
}

